package com.ict.txmsv2.services;

import com.ict.txmsv2.model.Exam;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yoleen
 * @date 2020/6/20 7:55
 */

@Service
public class ExamService {
    public List<Exam> getCoursesByEncoded(String encoded){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://jwc.sgu.edu.cn/jsxsd/xk/LoginToXk");
        List<NameValuePair> data = new ArrayList<>();
        //MTgxMjUwMzEwMjA=%%%aGFwcHl5eWw1MjA=
        data.add(new BasicNameValuePair("encoded",encoded));
        String responseHtml = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(data));
            CloseableHttpResponse response = httpClient.execute(httpPost);

            HttpGet httpGet = new HttpGet("http://jwc.sgu.edu.cn/jsxsd/kscj/cjcx_list");
            CloseableHttpResponse response1 = httpClient.execute(httpGet);

            responseHtml = EntityUtils.toString(response1.getEntity(), "utf-8");
        }catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println(html);

        Document document = Jsoup.parse(responseHtml);

        Element dataList = document.getElementById("dataList");
        if(dataList==null){
            return null;
        }
        Elements trs = dataList.getElementsByTag("tr");
        if(trs==null){
            return null;
        }
        List<Exam> list = new ArrayList<>();

        for (int i = 1; i < trs.size(); i++) {
            String[] strs = trs.get(i).text().split(" ");
//            System.out.println(Arrays.toString(strs));
            if(strs.length == 12){
                list.add(new Exam(Integer.parseInt(strs[0]),strs[1],strs[2],
                        strs[3], Double.parseDouble(strs[4]), Double.parseDouble(strs[5]), Integer.parseInt(strs[6]),
                        strs[7], Double.parseDouble(strs[8]),strs[9],strs[10],strs[11]));
            }
        }

        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
